<?php

namespace app\api\model;

use addons\epay\library\Service;
use think\Db;
use think\Log;
use think\Model;
use Yansongda\Pay\Pay;

/**
 *
 */
class Auction extends Model
{

    // 表名
    protected $name = 'auction';
    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    // 追加属性
    protected $append = [
        'start_time_text',
        'end_time_text',
        'status_text'
    ];


    public function getStatusList()
    {
        return [0 => '待开始', 1 => '进行中', 2 => '已结束', 3 => '已暂缓', 4 => '已中止', 5 => '已撤回', 6 => '已暂停'];
    }

    public function getStatusTextAttr($value, $data)
    {
        $value = $value ? $value : $data['status'];
        $list = $this->getStatusList();
        return $list[$value] ?? '';
    }



    public function getStartTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['start_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }


    public function getEndTimeTextAttr($value, $data)
    {
        $value = $value ?: ($data['end_time'] ?? '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    public function cronOpenAuction($auction_id)
    {
        $auction_info =  Auction::get($auction_id);

        if (!empty($auction_info)) {

            if ($auction_info[ 'status' ] == 0) {

                $auction_info->status = 1;
                $res = $auction_info->save();

                return [
                    'code'=>1,
                    'data'=>$res
                ];
            } else {
                return [
                    'code'=>1,
                    'msg'=>'拍卖活动已开启或者关闭'
                ];
            }
        } else {
            return [
                'code'=>1,
                'msg'=>'拍卖活动不存在'
            ];
        }

    }

    public function order_no(){
        $order_no = null;
        while (true) {
            $order_no = date('YmdHis') . mt_rand(1000, 9999);
            $exist_order_no = AuctionOrder::get(['final_order_no' => $order_no]);
            if (!$exist_order_no) {
                break;
            }
        }
        return $order_no;
    }


    public function invalidAuction($auction_id)
    {

        Db::startTrans();
        try {

            $auction_info =  Auction::get($auction_id);

            $auction_info->status = 2;
            $res = $auction_info->save();
            $bid_log = AuctionBidLog::where(['auction_id'=>$auction_id,'status'=>1])->find();
            if ($bid_log){
                $bid_log->is_winning = 1;
                $bid_log->save();
                //中标的订单改状态去付尾款
                $order = AuctionOrder::get($bid_log->order_id);
                $order->final_order_no = $this->order_no();
                $order->final_payment = bcsub($bid_log->price,$order->price,2);
                $order->order_status = 2;
                $order->order_status_name = '待补款';
                $order->save();

                //未中标的退回保证金
                $order_list = AuctionOrder::where('order_id','<>',$bid_log->order_id)
                    ->where(['pay_status'=>1,'is_refund'=>0])
                    ->field('order_id,order_no,price,is_refund,pay_status')->select();
                foreach ($order_list as $k=>$v){
                    //$res = $this->refundoperate($order->order_no, 'wechat',$v['price'],$v['price']);
                    //if ($res){
                        $order_info = AuctionOrder::get($v['order_id']);
                        $order_info->is_refund = 1;
                        $order_info->refund_time = time();
                        $order->order_status = 4;
                        $order->order_status_name = '未获拍';
                        $order_info->save();
                    //}
                }
            }
            Db::commit();

            return $res;
        } catch (\Exception $e) {
            Db::rollback();
            throw new \Exception($e->getMessage());
        }

    }

    public function refundoperate($order_sn, $paytype, $payamount,$refund)
    {
        $config = Service::getConfig($paytype);
        try {
            //$order = Order::getByOrderSn($order_sn);

            $response = Pay::wechat($config)->refund([
                'type'          => 'miniapp',
                'out_trade_no'  => $order_sn,
                'out_refund_no' => time(),
                'total_fee'     => $payamount * 100,
                'refund_fee'    => $refund * 100
            ]);

            if (!$response['result_code'] || $response['result_code'] != 'SUCCESS') {
                throw new \Exception(($response['err_code'] ?? '') . ':' . ($response['err_code_des'] ?? '未知退款错误'));
            }

        } catch (\Exception $e) {
            Log::write("[{$order_sn}]同步退款失败，失败原因：" . $e->getMessage(), 'refund');
            throw new \Exception("同步退款失败，失败原因：" . $e->getMessage());
        }

        return true;
    }

    public function lists($data)
    {

        $category_id = $data['category_id'];

        $sort = isset($data['sort']) ? $data['sort'] : '';

        $order = isset($data['order']) ? $data['order'] : '';

        $city_id = isset($data['city_id']) ? $data['city_id'] : '';

        $status = isset($data['status']) ? $data['status'] : 'all';

        $where = ['category_id'=>$category_id];

        if ($city_id){
            $where['city_id'] = $city_id;
        }

        if ($status!='all'){
            $where['status'] = $status;
        }

        if ($order != ''){
            if ($order=='new'){
                //最新发布
                $orderBy = 'createtime desc';
            } elseif ($order=='begin'){
                //即将开始
                $orderBy = 'status asc start_time asc';
            } elseif ($order=='end'){
                //即将结束
                $orderBy = 'end_time asc';
                /*$raw = "CASE
                    WHEN status = 1 AND end_time > " . time() . " THEN 0
                    WHEN status = 1 THEN 1
                    ELSE 2
                END ASC";*/

                $list = Auction::where($where)
                    ->field('auction_id,category_id,name,image,start_time,end_time,bid_count,status')
                    ->orderRaw("CASE 
                    WHEN status = 1 AND end_time > " . time() . " THEN 0
                    WHEN status = 1 THEN 1
                    ELSE 2
                END ASC")
                    ->order($orderBy)
                    ->paginate(10, false, ['query' => request()->get()]);

                return $list;
            } else {
                $orderBy = $order . ' ' . $sort;
            }

        } else {
            $orderBy = 'status asc createtime desc';
        }

        $list = Auction::where($where)
            ->field('auction_id,category_id,name,image,start_time,end_time,bid_count,status,price')
            ->order($orderBy)
            ->paginate(10, false, ['query' => request()->get()]);


        return $list;
    }

    public function mylists($data)
    {
        $user_id = $data['user_id'];


        $category_id = $data['category_id'];

        $sort = isset($data['sort']) ? $data['sort'] : '';

        $order = isset($data['order']) ? $data['order'] : '';

        $city_id = isset($data['city_id']) ? $data['city_id'] : '';

        $status = isset($data['status']) ? $data['status'] : 'all';

        $auction_id = AuctionOrder::where(['user_id'=>$user_id,'pay_status'=>1])->column('auction_id');

        if (count($auction_id)==0){
            return [];
        }

        $where = ['category_id'=>$category_id,'auction_id'=>['in',$auction_id]];

        if ($city_id){
            $where['city_id'] = $city_id;
        }

        if ($status!='all'){
            $where['status'] = $status;
        }

        if ($order != ''){
            if ($order=='new'){
                //最新发布
                $orderBy = 'createtime desc';
            } elseif ($order=='begin'){
                //即将开始
                $orderBy = 'status asc start_time asc';
            } elseif ($order=='end'){
                //即将结束
                $orderBy = 'end_time asc';
                /*$raw = "CASE
                    WHEN status = 1 AND end_time > " . time() . " THEN 0
                    WHEN status = 1 THEN 1
                    ELSE 2
                END ASC";*/

                $list = Auction::where($where)
                    ->field('auction_id,category_id,name,image,start_time,end_time,bid_count,status')
                    ->orderRaw("CASE 
                    WHEN status = 1 AND end_time > " . time() . " THEN 0
                    WHEN status = 1 THEN 1
                    ELSE 2
                END ASC")
                    ->order($orderBy)
                    ->paginate(10, false, ['query' => request()->get()]);

                return $list;
            } else {
                $orderBy = $order . ' ' . $sort;
            }

        } else {
            $orderBy = 'status asc createtime desc';
        }

        $list = Auction::where($where)
            ->field('auction_id,category_id,name,image,start_time,end_time,bid_count,status,price')
            ->order($orderBy)
            ->paginate(10, false, ['query' => request()->get()]);


        return $list;
    }
}
